<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
// use Common\ORG\Page,Common\ORG\AttUpload,Common\ORG\Excel;
// Knowledgeright manager
class KnowledgerightController extends BaseController {
    // knowledgeright list
    public function Index(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        if($this->m_is_admin){//is_admin right
            $callfun = M('knowledge_spot')->where(array('is_delete'=>array('neq',1)))->order('code asc')->select();
        }else{
            $arr = array();
            $callfunres = M('knowledge_spot')->where(array('is_level_one'=>1,'level_one_manager'=>$this->m_user['user_id'],'is_delete'=>array('neq',1)))->order('code asc')->select();
            if($callfunres){
                $callfunall = M('knowledge_spot')->field('code,knowledge_spot_id')->where(array('is_delete'=>array('neq',1)))->order('code asc')->select();
                if($callfunall){
                    foreach($callfunres as $key => $val){
                        foreach($callfunall as $k => $v){
                            if(substr($v['code'],0,2) == $val['code']){
                                $arr[] = $v['knowledge_spot_id'];
                             }
                        }
                    }                 
                }
            }
            if($arr){
                $callfun = M('knowledge_spot')->where(array('knowledge_spot_id'=>array('IN',$arr),'is_delete'=>array('neq',1)))->order('code asc')->select();
            }
        }
        $res['rcode'] = 1;
        $res['data'] = $callfun;    
         e_json($res);
    }

    // judge if knowledge node is exsit
    public function KnowledgeRightManage(){
        $res = array('rcode'=>0,'data'=>'','msg'=>'');
    }

    // add knowledge_spot
    public function AddKnowledgeSpot(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');	
        $wheres = $arr = array();
        $knowledgespotname = I('post.addknowledgespot','','trim');
        $knowledgespostcode = I('post.addknowledgecode','','trim');
        $knowledgespotuserid = I('post.GetUserID',false,'intval');
        if($knowledgespotuserid){
            $wheres['level_one_manager'] = $knowledgespotuserid;
            $wheres['is_level_one'] = 1;
        }
        $wheres['name'] = $knowledgespotname;
        $wheres['code'] = $knowledgespostcode;
        $wheres['is_delete'] = 0;
        $wheres['create_id'] = $this->m_user['user_id'];
        $rightres = M('knowledge_spot')->add($wheres);
        if($rightres){
            if(strlen($knowledgespostcode) == 2){
                $arr['sector_id'] = 1;
                $arr['right_type'] = 2;
                $arr['knowledge_spot_id'] = $rightres;
                $callfun = M('knowledge_spot_sector_right')->add($arr);
                if($callfun){
                    $res['rcode'] = 1;
                }
            }else{
                // 
            }
        }
        e_json($res);
    }

    // get userId
    public function LoginUserId(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        if($this->m_user['user_id']){
            $res['rcode'] = 1;
            $res['data'] = $this->m_user['user_id'];
         }
        e_json($res);
    }

    //get username
    public function GetUserName(){
         $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
         $usernickname = M('user')->field('user_id,nickname')->select();
         if($usernickname){
             $res['rcode'] = 1;
             $res['data'] = $usernickname;
         }
         e_json($res);
    }


    // edit knowledgespot
    public function EditKnowledgeSpot(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK','arr' => array());
        if($_SERVER['REQUEST_METHOD'] == 'GET' ){
            // $res['data'] = 'get';
            $knowledgespotid = I('get.id',false,'intval');
            $getdata = M('knowledge_spot') ->field('ks.*,us.nickname')
                                           ->alias('ks')
                                           ->join('LEFT JOIN user as us ON us.user_id = ks.level_one_manager')
                                           ->where(array('ks.knowledge_spot_id'=>$knowledgespotid))
                                           ->find();
            if(strlen($getdata['code']) == 2){
                $res['is_show'] = 1;
            }else{
                $res['is_show'] = 0;
            }
            if($getdata){
                $res['rcode'] = 1;
                $res['data'] = $getdata;
            }
        }else{
            $arr = $wheres = $arrSub = array();
            $knowledgespotid = I('post.knowledgespotid',false,'intval');
            $editknowledgespot = I('post.editknowledgespot','','trim');
            $editknowledgecode = I('post.editknowledgecode','','trim');
            $GetUserID = I('post.GetUserID',false,'intval');
            $editadminright = I('post.editadminright',false,'intval');
            if($GetUserID){
                $arr['level_one_manager'] = $GetUserID;
            }
            else{
                if(strlen($editknowledgecode) > 2 && $editadminright){
                    $arr['level_one_manager']= null;
                    $arr['is_level_one'] = null;
                }
            }
            if($knowledgespotid){
                $codesingal = M('knowledge_spot')->field('code')->where(array('knowledge_spot_id'=>$knowledgespotid))->find();
                $count = strlen($codesingal['code']);
                $callfun =  M('knowledge_spot')->field('code,knowledge_spot_id')->select();
                if(!empty($callfun)){
                    foreach($callfun as $key => $val){
                        if($val['code'] == $codesingal['code']){
                            // 
                            $arr['knowledge_spot_id'] = $knowledgespotid;
                            $arr['name'] = $editknowledgespot;
                            $arr['code'] = $editknowledgecode;
                        }else{
                            if(substr($val['code'],0,$count) == $codesingal['code']){
                                $arrSub[] = $val['knowledge_spot_id'];
                                $wheres[] = $val['code'];
                            }
                        }
                    }
                }
                $postdata = M('knowledge_spot')->save($arr);
                foreach($arrSub as $k => $v){
                    $subcount = strlen($wheres[$k])-$count;
                    if($subcount > 0){
                        $coderes =  $editknowledgecode.substr($wheres[$k],-$subcount);
                        $editres = M('knowledge_spot')->where(array('knowledge_spot_id'=>$v))->save(array('code'=>$coderes));
                        if($editres){
                            $res['arr'][] = 1;
                        }else{
                            $res['arr'][] = 2;
                        }
                    }
                }
                if($postdata && !in_array(2,$res['arr'])){
                    $res['rcode'] = 1;
                }             
            }
        }
        e_json($res);
    }

    // edit setting knowledge spot
    public function EditSettingKnowledgeSpot(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');   
        $knowledgelist = array();  
        if($_SERVER['REQUEST_METHOD'] == 'GET' ){
            $knowledge_spot_id = I('get.knowledge_spot_id',false,'intval');
            $res['data']['EditUserOnlyReadRights'] = array();
            $res['data']['EditUserWriteRights'] = array();
            $res['data']['readonly'] = array();
            $res['data']['write'] = array();
            $res['data'] = M('knowledge_spot_user_right')->field('knowledge_spot_user_right.*,user.nickname')
                                                         ->join('LEFT JOIN user ON user.user_id = knowledge_spot_user_right.user_id')
                                                         ->where(array('knowledge_spot_id'=>$knowledge_spot_id))
                                                         ->select();
            if($res['data']){
                foreach($res['data'] as $key => $val){
                    if($val['right_type'] == 1){
                        $res['data']['EditUserOnlyReadRights'][] = intval($val['user_id']); 
                        $res['data']['readonly'][] = $val['nickname']; 
                    }else{
                        $res['data']['EditUserWriteRights'][] = intval($val['user_id']);
                        $res['data']['write'][] = $val['nickname'];
                    }
                }
            }
        }else{
                $datalistreadonly = $datalistwrite =  array();
                $_POST['param']['EditUserOnlyReadRights'] ? $readonly = $_POST['param']['EditUserOnlyReadRights'] : '';
                $_POST['param']['EditUserWriteRights'] ? $write = $_POST['param']['EditUserWriteRights'] :'' ;
                $_POST['knowledge'] ? $knowledgespotid = $_POST['knowledge'] : '';
                // $clbl = M('knowledge_spot_user_right')->distinct(true)->field('user_id')->where(array('knowledge_spot_id'=>$knowledgespotid))->select();

                if($readonly){
                    $num = count($readonly);
                    foreach($readonly as $key=>$val){
                        $datalist[$key]['user_id'] = $val;
                        $datalist[$key]['right_type'] = 1;
                        $datalist[$key]['knowledge_spot_id'] = $knowledgespotid;
                    }            
                }

                if($write){
                    foreach($write as $key => $val){
                        $datalist[$key + $num]['user_id'] = $val;
                        $datalist[$key + $num]['right_type'] = 2;
                        $datalist[$key + $num]['knowledge_spot_id']= $knowledgespotid;
                    }            
                }

                M('knowledge_spot_user_right')->where(array('knowledge_spot_id'=>$knowledgespotid))->delete();
                if($datalist){
                    foreach($datalist as $key=>$val){//need to do better
                        $callback =  M('knowledge_spot_user_right')->add($val);  
                        if(!$callback){
                                e_json($res);
                        }else{
                                $res['rcode'] = 1;              
                        }
                    }                    
                }else{
                    $res['data'] = '您没有选择任何权限';
                }
            e_json($res);                  
        }
        e_json($res);
    }

    // get subcompany 
    public function getsubcompany(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        // $subcompany = M('sector')->field('sector_name,sector_id')->where(array('is_subcompany'=>1))->select();
        $wheres = array();
		$wheres['is_deleted'] = array('neq', 1);
	   $MSector = D('Admin/Sector');
	   $secs = $MSector->field("sector_id,info,sector_name,parent_company,parent_sector,manager_id")->where( $wheres )->select();
       $_secs = array();
    	foreach ($secs as $sc ){
            $_secs[$sc['sector_id']] = $sc;
        }
        $subcompany = list_to_tree($secs,'sector_id','parent_sector','_child', 0 );
        if($subcompany){
            $res['rcode'] = 1;
            $res['data'] = $subcompany;
        }
        e_json($res);
    }

    // get user of the sector
    public function GesUser(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> '');
        $sector_id = I('get.sector_id',false,'intval');
        $callsector = M('user') ->field('user_id,nickname')
                                ->where(array('sector_id'=>$sector_id))
                                ->select();
        if($callsector){
            $res['rcode'] = 1;
            $res['data'] = $callsector;
        }
        e_json($res);
    }

    // get sectortree
    public function GetSectorTree(){
        $res = array('rcode'=>0,'data'=>NULL,'sector'=>NULL, 'msg'=> 'OK');      
        $Mdo = D("Admin/Sector");
        $wheres = array();
        $wheres['is_deleted'] = array('eq', $Mdo::STATE_OK );
        $secs = $Mdo->field("sector_id,info,sector_name,parent_sector,manager_id")->where( $wheres )->select();
        $_secs = array();
        foreach( $secs as $sc ){
            $_secs[$sc['sector_id']] = $sc;
        }
        $arr = list_to_tree($secs,'sector_id','parent_sector','_child', 0 );  
        if($arr){
            $res['rcode'] = 1;
            $res['data'] = $arr; 
            $res['sector'] = $secs;   
        }
        e_json($res);
    }

    //sector knowledge_node setting
    public function SectorParam(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        $knowledge_spot_id = I('get.id',false,'intval');
        $res['data']['sectorreadonly'] = array();
        $res['data']['sectorwrite'] = array();
        $res['data'] = M('knowledge_spot_sector_right')->field('knowledge_spot_sector_right.*,sector.sector_name')
                                                        ->join('LEFT JOIN sector ON sector.sector_id = knowledge_spot_sector_right.sector_id')
                                                        ->where(array('knowledge_spot_sector_right.knowledge_spot_id'=>$knowledge_spot_id))
                                                        ->select();
        if($res['data']){
            foreach($res['data'] as $key => $val){
                if($val['right_type'] == 1){
                    $res['data']['sectorreadonly'][] = $val['sector_name']; 
                }else{
                    $res['data']['sectorwrite'][] = $val['sector_name'];
                }
            }
            $res['rcode'] = 1;
        }   
         e_json($res);
    } 

    //user knowledge_node setting
    public function UserParamRight(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        $knowledge_spot_id = I('get.id',false,'intval');
        $res['data']['readonly'] = array();
        $res['data']['write'] = array();
        $res['data'] = M('knowledge_spot_user_right')->field('knowledge_spot_user_right.*,user.nickname')
                                                        ->join('LEFT JOIN user ON user.user_id = knowledge_spot_user_right.user_id')
                                                        ->where(array('knowledge_spot_user_right.knowledge_spot_id'=>$knowledge_spot_id))
                                                        ->select();
        if($res['data']){
            foreach($res['data'] as $key => $val){
                if($val['right_type'] == 1){
                    $res['data']['readonly'][] = $val['nickname']; 
                }else{
                    $res['data']['write'][] = $val['nickname'];
                }
            }
            $res['rcode'] = 1;
        }   
         e_json($res);       
    }

    // sector right manage
    public function SectorManage(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        if($_SERVER['REQUEST_METHOD'] == 'GET' ){
            $knowledge_spot_id = I('get.knowledge_spot_id',false,'intval');
            $res['data']['EditSectorOnlyReadRights'] = array();
            $res['data']['EditSectorWriteRights'] = array();
            $res['data']['sectorreadonly'] = array();
            $res['data']['sectorwrite'] = array();
            $res['data'] = M('knowledge_spot_sector_right')->field('knowledge_spot_sector_right.*,sector.sector_name')
                                                         ->join('LEFT JOIN sector ON sector.sector_id = knowledge_spot_sector_right.sector_id')
                                                         ->where(array('knowledge_spot_sector_right.knowledge_spot_id'=>$knowledge_spot_id))
                                                         ->select();
            if($res['data']){
                foreach($res['data'] as $key => $val){
                    if($val['right_type'] == 1){
                        $res['data']['EditSectorOnlyReadRights'][] = intval($val['sector_id']); 
                        $res['data']['sectorreadonly'][] = $val['sector_name']; 
                    }else{
                        $res['data']['EditSectorWriteRights'][] = intval($val['sector_id']);
                        $res['data']['sectorwrite'][] = $val['sector_name'];
                    }
                }
            }            
        }else{
                $datalistreadonly = $datalistwrite =  array();
                $_POST['param']['EditSectorOnlyReadRights'] ? $readonly = $_POST['param']['EditSectorOnlyReadRights'] : '';
                $_POST['param']['EditSectorWriteRights'] ? $write = $_POST['param']['EditSectorWriteRights'] :'' ;
                $_POST['knowledge_id'] ? $knowledgespotid = $_POST['knowledge_id'] : '';
                // $clbl = M('knowledge_spot_user_right')->distinct(true)->field('user_id')->where(array('knowledge_spot_id'=>$knowledgespotid))->select();

                if($readonly){
                    $num = count($readonly);
                    foreach($readonly as $key=>$val){
                        $datalist[$key]['sector_id'] = $val;
                        $datalist[$key]['right_type'] = 1;
                        $datalist[$key]['knowledge_spot_id'] = $knowledgespotid;
                    }            
                }

                if($write){
                    foreach($write as $key => $val){
                        $datalist[$key + $num]['sector_id'] = $val;
                        $datalist[$key + $num]['right_type'] = 2;
                        $datalist[$key + $num]['knowledge_spot_id']= $knowledgespotid;
                    }            
                }

                M('knowledge_spot_sector_right')->where(array('knowledge_spot_id'=>$knowledgespotid))->delete();
                if($datalist){
                    foreach($datalist as $key=>$val){//need to do better
                        $callback =  M('knowledge_spot_sector_right')->add($val);  
                        if(!$callback){
                                e_json($res);
                        }else{
                                $res['rcode'] = 1;              
                        }
                    }                    
                }else{
                    $res['data'] = '您没有选择任何权限';
                }
            e_json($res);   
        }
        e_json($res);    
    }

    // get knowledge node name
    public function GetNodeName(){
        $res = array('rcode'=>0,'data'=>null,'mag'=>'');
        $knowledge_spot_id = I('get.id',false,'intval');
        if($knowledge_spot_id){
            $callfun = M('knowledge_spot')->field('name,code')->where(array('knowledge_spot_id'=>$knowledge_spot_id))->find();
        } 
        if($callfun){
            $callfunallcompany = M('knowledge_spot_sector_right')->where(array('sector_id'=>1,'knowledge_spot_id'=>$knowledge_spot_id,'right_type'=>2))->count();
            if($callfunallcompany){
                if(strlen($callfun['code']) == 2){
                    if($this->m_is_admin){
                        $res['hide_setting'] = 1;
                        $res['is_hide'] = 0;
                    }else{
                        $res['hide_setting'] = 1;
                        $res['is_hide'] = 1;
                    }
                }else{
                    $res['hide_setting'] = 0;
                    $res['is_hide'] = 0;
                }
            }else{
                $callfunsec = M('knowledge_spot_sector_right')->where(array('sector_id'=>$this->m_user['sector_id'],'knowledge_spot_id'=>$knowledge_spot_id,'right_type'=>2))->count();
                if($callfunsec){
                    if(strlen($callfunsec['code']) == 2){
                        if($this->m_is_admin){
                            $res['hide_setting'] = 1;
                            $res['is_hide'] = 0;
                        }else{
                            $res['hide_setting'] = 1;
                            $res['is_hide'] = 1;
                        }
                    }else{
                        $res['hide_setting'] = 0;
                        $res['is_hide'] = 0;
                    }                   
                }else{
                    $callfunuser = M('knowledge_spot_user_right')->where(array('user_id'=>$this->m_user['user_id'],'knowledge_spot_id'=>$knowledge_spot_id,'right_type'=>2))->count();
                    if($callfunuser){
                        if(strlen($callfunsec['code']) == 2){
                            if($this->m_is_admin){
                                $res['hide_setting'] = 1;
                                $res['is_hide'] = 0;
                            }else{
                                $res['hide_setting'] = 1;
                                $res['is_hide'] = 1;
                            }
                        }else{
                            $res['hide_setting'] = 0;
                            $res['is_hide'] = 0;
                        }  
                    }else{

                    }
                }
            }
            $res['rcode'] = 1;
            $res['data'] = $callfun;            
        }
       
        e_json($res);
    }

    // delete knowlege node
    public function DeleteKnowledgeNode(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');       
        $returnsign = $knowledgeid = array();
        $code = I('post.code','','trim');
        $callfun = M('knowledge_spot')->where(array('is_delete'=>array('neq',1)))->select();
        $num = strlen($code);
        foreach($callfun as $key => $val){
           if(strncmp($code,$val['code'],$num) == 0){
               $returnsign[] = $val['knowledge_spot_id'];
           } 
        }
        if($returnsign){
            $resfunknowledge = M('knowledge')->field('knowledge_id')->where(array('knowledge_spot_id'=>array('IN',$returnsign)))->select();
            if($resfunknowledge){
                foreach($resfunknowledge as $key =>$val){
                    $knowledgeid[] = $val['knowledge_id'];
                }
            }
            if($knowledgeid){
                M('knowledge_file')->where(array('knowledge_id'=>array('IN',$knowledgeid)))->save(array('is_delete'=>1));            
            }  
            // if($returnsign){
            M('knowledge')  ->alias('a') ->where(array('a.knowledge_spot_id'=>array('in',$returnsign)))->save(array('a.is_delete'=>1));                
            M('knowledge_spot')->where(array('knowledge_spot_id'=>array('in',$returnsign)))->save(array('is_delete'=>1));
            M('knowledge_spot_sector_right')->where(array('knowledge_spot_id'=>array('in',$returnsign)))->delete();
            M('knowledge_spot_user_right')->where(array('knowledge_spot_id'=>array('in',$returnsign)))->delete();
            // }             
        }
        e_json($code);        
    }

    // verify code range
    public function  CodeRange(){
        $code = I('post.code',false,'trim');
        $code = substr($code,0,2);
        $arr = array();
        if($this->m_is_admin){
            $coderang= true;
        }else{
            $callfunres = M('knowledge_spot')->field('code')->where(array('is_level_one'=>1,'level_one_manager'=>$this->m_user['user_id'],'is_delete'=>array('neq',1)))->order('code asc')->select();
            if($callfunres){
                foreach($callfunres as $key => $val){
                    $arr[] = $val['code'];
                    if(in_array(substr($code,0,2),$arr)){
                        $coderang = true;
                    }else{
                        $coderang = false;
                    }
                }
            }         
        }
        e_json($coderang);
    }

    // verify code same
    public function IsSameCode(){
        $is_samecode = true;
        $is_same = I('post.code',false,'trim');
        $arr = array();
        $callfunres = M('knowledge_spot')->field('code')->where(array('is_delete'=>array('neq',1)))->order('code asc')->select();
        if($callfunres){
            foreach($callfunres as $key =>$val){
                $arr[] = $val['code'];
            }
        }
        if($arr){
            if(in_array($is_same,$arr)){
                $is_samecode = false;
            }else{
                $is_samecode = true;
            }
        }   
        e_json($is_samecode);   
    }

    // get user nickname
    public function getnickname(){
        $res = array('rcode'=>0,'data'=>'','msg'=>'');
        $user_id = I('post.user_id',false,'intval');
        if($user_id){
            $callfun = M('user')->field('nickname')->where(array('user_id'=>$user_id))->find();
        }
        if($callfun){
            $res['rcode'] = 1;
            $res['data'] = $callfun['nickname'];
        }
        e_json($res);
    }

    // Exist Parent Node
    public function ExistParentNode(){
        $wheres = array();
        $code = I('post.code','','trim');
        $knowledgeid = I('post.knowledge_spot_id',false,'intval');
        if(strlen($code) != 2){
           $wheres['code'] = substr($code,0,strlen($code)-2);
           $wheres['is_delete'] = array('neq',1);
           $callfun = M('knowledge_spot')->field('knowledge_spot_id,code')->where($wheres)->find();
           if($callfun){
                if($callfun['knowledge_spot_id'] == $knowledgeid && strlen($code) > strlen($callfun['code']) ){
                    $exist = false;
                }else{
                    $exist = true;                    
                }
           }else{
               $exist = false;
           }
        }else{
            $exist = true;
        }
         e_json($exist);
    }

    // get code of user
    public function CodeOfUser(){
        $user_id = I('post.user_id',false,'intval');
        if($user_id){
            $callfun = M('knowledge_spot')->field('code')->where(array('knowledge_spot_id'=>$user_id))->find();
        }
        if($callfun){
            $user_id = intval($callfun['code']);
        }
        e_json($user_id);
    }

    // validate code is repeat
    public function IsRepeat(){
        $res = array('rcode'=>0,'data'=>'','msg'=>'');
        $code = I('post.code','','trim');
        $codenow = I('post.codenow','','trim');
        if($code){
            if($codenow){
                if($code == $codenow){
                    $codecompare = true;
                }else{
                    $callfun = M('knowledge_spot')->where(array('code'=>$codenow,'is_delete'=>array('neq',1)))->count();
                    if($callfun){
                        $codecompare = false;
                    }else{
                        $codecompare = true;
                    }
                }
            }
        }
        e_json($codecompare);
    }
}
?>